package com.lagou.tomcat.classloader;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/7/15 上午8:31
 */
public class WebappClassLoader extends ClassLoader{

    private final String sourceRoot;

    public WebappClassLoader(String sourceRoot) {
        super();
        this.sourceRoot = "file:" + sourceRoot + "/";
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classLocation = sourceRoot + name.replace('.', '/') + ".class";
        byte[] bytes = null;
        try {
            Path path = Paths.get(new URI(classLocation));
            bytes = Files.readAllBytes(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Class<?> clz = defineClass(name, bytes, 0, bytes.length);
        return clz;
    }
}
